#!/bin/sh
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#

#
# Run a simple backup of the Bacula build directory then migrate it
#   to another device.
#
# Test copy a job that spans two Volumes
#
# This script uses the virtual disk autochanger
#
TestName="copy-jobspan-initial-label-wait-test"
JobName=CopyJobSpanInitialLabelWaitSave
. scripts/functions


scripts/cleanup
scripts/copy-migration-confs
scripts/prepare-disk-changer
echo "${cwd}/build" >${cwd}/tmp/file-list
cp ${cwd}/bin/bacula-sd.conf ${cwd}/tmp/1
sed "s%# Maximum File Size%  Maximum File Size%" ${cwd}/tmp/1 >${cwd}/bin/bacula-sd.conf
sed 's/migrate/copy/g' ${cwd}/bin/bacula-dir.conf > ${cwd}/tmp/1
sed 's/Migrate/Copy/g' ${cwd}/tmp/1 > ${cwd}/bin/bacula-dir.conf
cp ${cwd}/bin/bacula-dir.conf ${cwd}/tmp/1
awk '{ print $0; } /Name = Full/ { print "  Maximum Volume Bytes = 30M"; }' ${cwd}/tmp/1 > bin/bacula-dir.conf

change_jobname NightlySave $JobName
start_test

#
# Note, we first backup into Pool Default,
#          then Copy into Pool Full.
#              Pool Default uses Storage=File
#              Pool Full    uses Storage=DiskChanger

# Write out bconsole commands
cat <<END_OF_DATA >${cwd}/tmp/bconcmds
@output /dev/null
messages
@$out ${cwd}/tmp/log1.out
@#setdebug level=10 dir
@#setdebug level=100 storage=File
setdebug level=100 fd
label storage=File volume=FileVolume001 Pool=Default
label storage=File volume=FileVolume002 Pool=Default
update Volume=FileVolume001 MaxVolBytes=3000000 pool=Default
list volumes
@#
run job=$JobName yes
@#run job=$JobName yes
wait
list volumes
@#setdebug level=200 dir
setdebug level=70 storage=File
@# should migrate both Volumes
run job=copy-job yes
wait mount
label storage=DiskChanger volume=ChangerVolume001 slot=1 Pool=Full drive=0
wait mount
label storage=DiskChanger volume=ChangerVolume002 slot=2 Pool=Full drive=0
wait
purge volume=FileVolume001
purge volume=FileVolume002
list volumes
list jobs
messages
wait
@#
@# now do a restore
@#
@# Check if JobMedia OK (run under Aligned)
sql
select jobid, mediaid, firstindex,lastindex,volindex from JobMedia order by jobid,volindex;
select * from JobMedia order by jobid,volindex;

@$out ${cwd}/tmp/log2.out
restore where=${cwd}/tmp/bacula-restores select storage=DiskChanger
unmark *
mark *
done
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File
stop_bacula

check_two_logs
check_restore_diff
end_test
